<?php

class AccessController extends St_Controller_Action_Admin {

    public function init() {
        parent::init();
        if ($this->auth->hasIdentity() && (St_Registry::getActionName() != "logout") && (St_Registry::getActionName() != "deny")) {
            $this->_redirect("index");
        }
        $this->_helper->layout()->setLayout("login_layout");
    }

    public function indexAction() {
        
    }

    public function loginSubmitAction() {
        $msg = "";
        $user = $this->_getParam("user", false);
        if (!isset($user['email']) || $user['email'] == "") {
            $msg = "Can't find user information";
            $this->_forward("index", "access");
        }
        if ($user['email']) {

            Zend_Loader::loadClass("St_Auth_Adapter");
            $authAdapter = new St_Auth_Adapter ( );
            $authAdapter->setUserInfo($user ['email'], $user ['Password']);
            $result = $this->auth->authenticate($authAdapter);
            //var_dump($result);
            //die;
            if ($result->isValid()) {
                $user = $this->_getCurrentUser();
                print_r($user);
                $this->logger->log($user['email'] . " logged in", $user['UserID']);
                $schoolObj = St_Registry::getDB();
                $datas = $schoolObj->fetchRow("SELECT * from user where email='" . $user ['email'] . "'");
                //die;
                $this->_redirect("index");
            } else {
                $this->logger->log($user['email'] . " logged in fail");
                $this->view->username = $user['nickName'];
                $this->view->password = $user['Password'];
                $msg = "Login fail!!!";
                $this->_forward("index", "access");
            }
        } else {
            $this->_forward("index");
        }
        $this->view->msg = $msg;
    }

    public function logoutAction() {
        $user = $this->_getCurrentUser();
        $this->logger->log($user[nickName] . " logged out");
        $this->auth->clearAuthInfo();
        $this->_redirect("access");
    }

    public function denyAction() {
        
    }

    public function forgotpasswordAction() {
        $db = St_Registry::getDB();
        $user = $this->_getParam("user", false);
        if (!empty($user)) {
            $select = $db->select()
                    ->from(array('u' => 'user'))
                    ->where("nickName like('{$user['UserName']}') AND Email like('{$user['Email']}')")
            ;
            if ($result = $db->fetchRow($select)) {
                $userID = $result['UserID'];
                $newPassword = St_Registry::generateRandomPassword(12);
                $data['Password'] = md5($newPassword);
                Zend_Loader::loadClass("St_User");
                $userObj = new St_User ();
                if($userObj->update($data, "UserID = {$userID}")){
                    $libPath = realpath(APPLICATION_PATH . '/../../library/');
                    require_once($libPath . "/ses/ses.php");
                    $ses = new SimpleEmailService('AKIAJ2KSOHO54GRQULVA', '4OEyJ/zja4HMZTAxvTp2Q9R/UlPW7x2hbGQybLKr');
                    $m = new SimpleEmailServiceMessage();
                    $ses->enableVerifyPeer(false);                
                    $m->setSubject("Forgot Password");
                    $message = "
                        Hello {$result['nickName']} <br>
                        Your new password is: {$newPassword}<br>
                        ";
                    $m->setMessageFromString('', $message); // option 1: plain text, option 2: html

                    $m->setFrom("Mick<mick@slopetracker.no>");

                    $m->addTo($result['nickName'] . "<" . trim($result['Email']) . ">");
                    if ($ses->sendEmail($m)) {
                        $this->view->msg = "Please check your email to receive new password";
                    }else{
                        $this->view->msg = "Mail system error please try it again";
                    }                    
                }else{
                    $this->view->msg = "There's an error in system";
                }
                
            } else {
                $this->view->msg = "Your username or your email is incorrect";
            }
        }
    }

}

